package com.hjy.demo.web.controller;

import com.hjy.demo.pojo.User;
import com.hjy.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginController {

    @Resource
    private UserService userService;

    @RequestMapping(value = {"/","/login"})
    public String login(){
        return "login";
    }
    @GetMapping(value = "/main")
    public String main(){
        return "main";
    }

    @PostMapping(value = "/dologin")
    public String doLogin(String usrName, String usrPassword, HttpServletRequest request, Map<String, Object> map, HttpSession session){
        User user=null;
        try {
            //此处不再处理登录，由shiro进行处理
            AuthenticationToken token = new UsernamePasswordToken(usrName,usrPassword);
            SecurityUtils.getSubject().login(token);    //调用Shiro认证
            user = (User)SecurityUtils.getSubject().getPrincipal();
            //注意此处session.setAttribute中key的值
            //需要和AuthorizationInterceptor拦截器session的key一直
            session.setAttribute("user",user);
        }catch (IncorrectCredentialsException ik){
            map.put("message","密码错误"+ik.getMessage());
            return "login";
        }catch (Exception e){
            map.put("message",e.getMessage());
            return "login";
        }
        return "main";
    }

    @GetMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        //调用登出方法
        SecurityUtils.getSubject().logout();
        return "login";
    }

    @RequestMapping("/403")
    public String error(){
        return "403";
    }
}
